<template>
  <div
    class="detail"
    v-track
    event-type="browse_article"
    :event-id="route.params.id"
  >
    <BreadCrumb>
      <template v-slot:first>首页</template>
      <template v-slot:second>文章</template>
      <template v-slot:third>{{ article.title }}</template>
    </BreadCrumb>
    <div class="author">
      <img :src="article.author.avatar" alt="作者" class="avatar" />
      <span class="nickname">{{ article.author.nickname }}</span>
      <div class="time">
        <svg class="icon shijian" aria-hidden="true">
          <use xlink:href="#icon-31shijian"></use>
        </svg>
        <span>发布于&nbsp;{{ formatCreateAt(article.createAt) }}</span>
      </div>
      <div class="address">
        <svg class="icon dizhi" aria-hidden="true">
          <use xlink:href="#icon-dizhi"></use>
        </svg>
        <span>{{ article.author.address }}</span>
      </div>
    </div>
    <div class="d_main">
      <div
        class="d_lf"
        v-html="markdownToHtml(article.mdContent)"
        ref="articleRef"
      ></div>
      <div class="d_rg" v-if="!appStore.isMobile">
        <ArticleTitle>
          <template #icon>
            <svg class="icon book" aria-hidden="true">
              <use xlink:href="#icon-book2"></use>
            </svg>
          </template>
          <template #title>类型</template>
        </ArticleTitle>
        <p>{{ article.type_name }}</p>
        <ArticleTitle>
          <template #icon>
            <svg class="icon book" aria-hidden="true">
              <use xlink:href="#icon-24gf-tags2"></use>
            </svg>
          </template>
          <template #title>标签</template>
        </ArticleTitle>
        <p>
          <i v-for="item in article.labels" :key="item.id"
            >#{{ item.label }}&nbsp;&nbsp;
          </i>
        </p>
        <ArticleTitle>
          <template #icon>
            <svg class="icon book" aria-hidden="true">
              <use xlink:href="#icon-book1"></use>
            </svg>
          </template>
          <template #title>目录</template>
        </ArticleTitle>
        <div id="toc"></div>
      </div>
    </div>
    <Comment :comments="comments" @onComment="onComment" @onReply="onReply" />
  </div>
</template>

<script setup>
  import { onBeforeMount, onMounted, nextTick, ref, reactive } from 'vue'
  import { useRoute } from 'vue-router'
  import { queryArticleRequest } from '@/network/api/home'
  import {
    articleCommentRequest,
    replyCommentRequest,
  } from '@/network/api/comment'
  import { localCache } from '@/utils/cache'
  import Message from 'vue-m-message'
  import BreadCrumb from '@/components/BreadCrumb.vue'
  import ArticleTitle from '@/components/ArticleTitle.vue'
  import Comment from '@/components/Comment.vue'
  import Prism from 'prismjs'
  import '@/assets/css/prism-aurora-future.css'
  import markdownToHtml from '@/utils/md2Html'
  import tocbot from 'tocbot'
  import formatComments from '@/utils/comments'
  import useUserStore from '@/store/userStore'
  import useAppStore from '@/store/appStore'
  const userStore = useUserStore()
  const appStore = useAppStore()
  const article = reactive({
    mdContent: '',
    title: '',
    type_name: '',
    labels: [],
    author: {},
    createAt: '',
  })
  let comments = ref([])
  const articleRef = ref()
  const route = useRoute()
  const initTocbot = () => {
    let nodes = articleRef.value.children
    if (nodes.length) {
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i]
        // 正则匹配 所有标题 添加id 方便跳转目录
        let reg = /^H[1-4]{1}$/
        if (reg.exec(node.tagName)) {
          node.id = i
        }
      }
    }
    tocbot.init({
      tocSelector: '#toc',
      contentSelector: '.d_lf',
      headingSelector: 'h1, h2, h3',
      onClick: function (e) {
        e.preventDefault()
      },
    })
  }
  onBeforeMount(async () => {
    const result = await queryArticleRequest(route.params.id)
    console.log(result)
    for (const key in result.result.article) {
      article[key] = result.result.article[key]
    }
    comments.value = formatComments(result.result.comments)

    nextTick(() => {
      Prism.highlightAll() // 高亮代码
      initTocbot() // 目录跳转
    })
  })
  // 评论处理
  const onComment = async comment => {
    // 验证登录状态
    if (!userStore.isLogin || !localCache.getCache('user'))
      return Message.warning('请先登录~')
    if (!comment) return Message.warning('未检测到文字~')
    const result = await articleCommentRequest(route.params.id, comment)
    Message.success(result.msg)
    // 更新
    const res = await queryArticleRequest(route.params.id)
    comments.value = formatComments(res.result.comments)
  }
  // 回复处理
  const onReply = async (reply, id) => {
    // 验证登录状态
    if (!userStore.isLogin || !localCache.getCache('user'))
      return Message.warning('请先登录~')
    if (!reply) return Message.warning('未检测到文字~')
    const result = await replyCommentRequest(route.params.id, id, reply)
    Message.success(result.msg)
    // 更新
    const res = await queryArticleRequest(route.params.id)
    comments.value = formatComments(res.result.comments)
  }
  // 时间格式化函数
  const formatCreateAt = v => {
    let date = new Date(v)
    return (
      date.getMonth() +
      1 +
      '月' +
      (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) +
      ', ' +
      date.getFullYear()
    )
  }
</script>

<style lang="less">
  @media only screen and (min-width: 991px) {
    .detail {
      width: 100%;
      .author {
        display: flex;
        margin: 15px 0;
        padding-left: 12px;
        font-size: 16px;
        span {
          font-weight: 700;
          margin: 0 12px;
        }
        .avatar {
          width: 30px;
          height: 30px;
          border-radius: 999px;
        }
      }
      .d_main {
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: flex-start;
        font-size: 16px;
        .d_lf {
          width: 78%;
          padding: 56px;
          background: var(--background-secondary);
          border-radius: 16px;
          img {
            width: 100%;
          }
          p {
            margin: 5px 0;
            line-height: 2;
          }
          ul {
            li {
              position: relative;
              padding: 12px;
              line-height: 2;
              &::before {
                content: '';
                position: absolute;
                left: -8px;
                top: 22px;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: var(--text-accent);
              }
            }
          }
          ol {
            li {
              margin: 14px 0;
              padding-left: 5px;
              &::marker {
                font-weight: 700;
                color: var(--text-accent);
              }
            }
          }
          h1,
          h2,
          h3,
          h4,
          h5,
          h6 {
            position: relative;
            color: var(--text-bright);
            font-weight: 600;
            margin: 40px 0;
            &::after {
              content: '';
              height: 4px;
              position: absolute;
              bottom: -15px;
              left: 0;
              width: 90px;
              background: var(--main-gradient);
            }
          }
        }
        .d_rg {
          width: 20%;
          padding: 32px;
          border-radius: 16px;
          background-color: var(--background-secondary);
          --tw-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
            0 10px 10px -5px rgba(0, 0, 0, 0.04);
          box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000),
            var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
        }
      }
    }
  }
  @media only screen and (max-width: 990px) {
    .detail {
      width: 100%;
      .author {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin: 15px 0;
        padding-left: 12px;
        font-size: 14px;

        .avatar {
          width: 30px;
          height: 30px;
          border-radius: 999px;
          margin-right: 12px;
        }
        .time {
          margin-left: 12px;
        }
        .address {
          margin-top: 8px;
        }

        .address,
        .time {
          display: flex;
          justify-content: center;
          align-items: center;
          span {
            margin-left: 6px;
          }
        }
      }
      .d_main {
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: flex-start;
        font-size: 14px;
        .d_lf {
          width: 100%;
          padding: 16px;
          background: var(--background-secondary);
          border-radius: 16px;
          img {
            width: 100%;
          }
          p {
            margin: 5px 0;
            line-height: 1.5;
          }
          ul {
            li {
              position: relative;
              padding: 7px 0 7px 18px;
              line-height: 1.6;
              &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 12px;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: var(--text-accent);
              }
            }
          }
          ol {
            li {
              margin: 14px 0;
              padding-left: 5px;
              font-size: 14px;
              line-height: 1.5;
              &::marker {
                font-weight: 700;
                color: var(--text-accent);
              }
            }
          }
          h1,
          h2,
          h3,
          h4,
          h5,
          h6 {
            position: relative;
            color: var(--text-bright);
            font-weight: 600;
            line-height: 1.4;
            padding-bottom: 16px;
            &::after {
              content: '';
              height: 4px;
              position: absolute;
              bottom: 5px;
              left: 0;
              width: 90px;
              background: var(--main-gradient);
            }
          }
          h1 {
            font-size: 26px;
          }
          h2 {
            font-size: 23px;
          }
          h3 {
            font-size: 20px;
          }
          h4 {
            font-size: 18px;
          }
          h5 {
            font-size: 16px;
          }
        }
      }
    }
  }
  #toc {
    ol {
      margin: 0;
      padding: 0;
      list-style: disc;
      padding-left: 12px;
      li {
        font-weight: 500;
        font-size: 14px;
        line-height: 1.5;
        padding: 5px 0;
      }
    }
    a {
      color: inherit;
      text-decoration: inherit;
    }
  }
</style>
